﻿/*
 * Author: Jerry Bai
 * Create Date: 2011/7/18
 * Description: Extend String class.
 * Licence: BSD
 */
using System;
using System.Web;
using System.Text.RegularExpressions;

namespace AgileShare.Framework.Library.Helpers
{
    /// <summary>
    /// String扩展方法
    /// </summary>
    public static class StringUtility
    {
        public static string NoHtml(this String Htmlstring)
        {
            //删除脚本
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "",
              RegexOptions.IgnoreCase);
            //删除HTML
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", "   ",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "",
              RegexOptions.IgnoreCase);

            Htmlstring.Replace("<", "");
            Htmlstring.Replace(">", "");
            //Htmlstring.Replace("\r\n", "");
            Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();

            return Htmlstring;
        }

        /// <summary>
        /// 转换SQL Like语句，文本中含有“[”、“%”等匹配符，成普通字符
        /// </summary>
        /// <param name="rawString"></param>
        /// <returns></returns>
        public static string ConvertSQLLikeText(this String rawString)
        {
            return rawString.Replace("[", "[[]").Replace("%", "[%]").Replace("^", "[^]").Replace("_", "[_]");
        }

        /// <summary>
        /// 对手机号进行掩码处理
        /// </summary>
        /// <param name="rawString"></param>
        /// <returns></returns>
        public static string MaskCellPhone(this String rawString)
        {
            string result = rawString;
            if(String.IsNullOrEmpty(rawString))
            {
                result = "";
            }
            else
            {
                // 手机号
                if (rawString.Length >= 11)
                {
                    // 13300000012
                    result = rawString.Substring(0, rawString.Length - 8) + "****" + rawString.Substring(rawString.Length - 4, 4);
                }
            }
            return result;
        }

        /// <summary>
        /// 过滤HTML代码
        /// </summary>
        /// <param name="rawString">原始字符串</param>
        /// <returns></returns>
        public static string FilterHTMLCode(this String rawString)
        {
            return FilterHTMLCode(rawString, false);
        }

        /// <summary>
        /// 过滤HTML代码
        /// </summary>
        /// <param name="rawString">原始字符串</param>
        /// <param name="needHTMLDecode">需要HTML解码</param>
        /// <returns></returns>
        public static string FilterHTMLCode(this String rawString, bool needHTMLDecode)
        {
            if (String.IsNullOrEmpty(rawString))
            {
                return "";
            }
            else
            {
                string result = rawString;
                if (needHTMLDecode)
                {
                    result = HttpUtility.HtmlDecode(result);
                }
                result = Regex.Replace(rawString, @"<[^>]+>", "", RegexOptions.IgnoreCase);
                return result;
            }
        }

        /// <summary>
        /// 获取特定长度的字符串
        /// </summary>
        /// <param name="rawString">原始字符串</param>
        /// <param name="maxCharSize">字符长度，长度至少取2个字符</param>
        /// <returns></returns>
        public static string SpecifiedLengthString(this String rawString, int maxCharSize)
        {
            return SpecifiedLengthString(rawString, maxCharSize, true);
        }

        /// <summary>
        /// 获取特定长度的字符串
        /// </summary>
        /// <param name="rawString">原始字符串</param>
        /// <param name="maxCharSize">字符长度，长度至少取2个字符</param>
        /// <param name="showPoint">是否显示...</param>
        /// <returns></returns>
        public static string SpecifiedLengthString(this String rawString, int maxCharSize, bool showPoint)
        {
            if (String.IsNullOrEmpty(rawString))
            {
                return "";
            }
            else
            {
                // 长度至少取2个字符
                if (maxCharSize < 2)
                {
                    maxCharSize = 2;
                }
                string result = rawString;
                int currentByteLength = 0;
                for (int i = 0; i < result.Length; i++)
                {
                    currentByteLength += IsASCII(result[i]) ? 1 : 2;
                    // 截断字符后还有字符未显示出来，则减去
                    if (i > 1 && i < result.Length - 1)
                    {
                        if (showPoint)
                        {
                            if (currentByteLength >= maxCharSize * 2)
                            {
                                int newByteLength = currentByteLength;
                                int delCharCount = 0;
                                while (currentByteLength - newByteLength <= 3)
                                {
                                    newByteLength -= (IsASCII(result[i - delCharCount]) ? 1 : 2);
                                    delCharCount++;
                                }
                                result = result.Substring(0, i - delCharCount + 1) + "...";
                                break;
                            }
                        }
                        else
                        {
                            if (currentByteLength == maxCharSize * 2)
                            {
                                result = result.Substring(0, i + 1);
                            }
                            else if (currentByteLength > maxCharSize * 2)
                            {
                                result = result.Substring(0, i);
                            }
                        }
                    }
                }
                return result;
            }
        }

        /// <summary>
        /// 是否为ASCII码
        /// </summary>
        /// <param name="rawChar"></param>
        /// <returns></returns>
        private static bool IsASCII(char rawChar)
        {
            return Convert.ToInt32(rawChar) < 256 && rawChar != '—';
        }

        /// <summary>
        /// 将字符转成16进制表示。如&#9c8a;&#f3;
        /// </summary>
        /// <param name="rawString"></param>
        /// <returns></returns>
        public static string ToHtmlHex(this String rawString)
        {
            string result = "";
            if (!String.IsNullOrEmpty(rawString))
            {
                foreach (var currentChar in rawString.ToCharArray())
                {
                    result += CharToHtmlHex(currentChar);
                }
                return rawString;
            }
            return result;
        }

        private static string CharToHtmlHex(char rawChar)
        {
            string result = "";
            int tmp = Convert.ToInt32(rawChar);
            if (tmp < 256)
            {
                result = "&#" + Convert.ToByte(tmp).ToString("H") + ";";
            }
            else
            {
                int highNum = tmp >> 8;
                int lowNum = tmp << 8;
                result = "&#" + Convert.ToByte(highNum).ToString("H") + Convert.ToByte(lowNum).ToString("H") + ";";
            }
            return result;
        }
    }
}
